package com.xzk.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Classname ConsumerController
 * @Description TODO
 * @Date 2020/9/22 11:24
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    //@HystrixCommand(fallbackMethod = "queryByIdFallback")
    @HystrixCommand
    public String queryById(@PathVariable Long id){
        //String url = "http://localhost:9091/user/" + id;
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" +id;
        if (id == 1){
            throw new RuntimeException("服务熔断测试...");
        }
        String url = "http://user-service/user/" + id;

        return restTemplate.getForObject(url, String.class);
    }

    //服务降级的方法
    public String queryByIdFallback(Long id){
        log.error("查询用户信息失败，id:" + id);
        return "当前网络比较拥挤,请稍后再试...";
    }

    //默认服务降级的方法
    public String defaultFallback(){
        return "当前网络拥挤，请稍后再试...";
    }

}
